﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Text.RegularExpressions;
using System.Data;
using System.ComponentModel;
using System.Collections;
using System.Web.Script.Serialization;
using System.Xml.Serialization;


namespace App_Utils
{
    public class clsUtils
    {
        public static string getSQLinString(string[] inStrings)
        {
            string resultString = "";
            for (int i = 0; i < inStrings.Count(); i++)
            {
                if (resultString == "") resultString = "('" + inStrings[i] + "'";
                else resultString = resultString + ",'" + inStrings[i] + "'";
            }
            return resultString + ")";
        }

        //To Create Directory.
        public static string CreateNewDirectory(string Path)
        {
            Directory.CreateDirectory(Path);
            return Path;
        }

        //To Delete Directory
        public static void DeleteDirectory(string path, bool isWeb = true)
        {
            if (isWeb)
            {
                //to disable session out on directory structure change
                PropertyInfo p = typeof(System.Web.HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
                object o = p.GetValue(null, null);
                FieldInfo f = o.GetType().GetField("_dirMonSubdirs", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
                object monitor = f.GetValue(o);
                MethodInfo m = monitor.GetType().GetMethod("StopMonitoring", BindingFlags.Instance | BindingFlags.NonPublic);
                m.Invoke(monitor, new object[] { });
                //Ends Here
            }
            if (Directory.Exists(path))
                Directory.Delete(Path.GetDirectoryName(path), true);
        }


        public static string getTimeStemp()
        {
            return DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
        }

        public static string getRandomNumber()
        {
            Random _r = new Random();
            return _r.Next().ToString();
        }

        //To Empty Directory
        public static void EmptyDirectory(string path, bool isWeb = true)
        {
            DirectoryInfo di = new DirectoryInfo(path);
            if (di.Exists)
            {
                foreach (FileInfo fil in di.GetFiles())
                {
                    fil.Delete();
                }
                foreach (DirectoryInfo idi in di.GetDirectories())
                {
                    DeleteDirectory(idi.FullName, isWeb);
                }
            }

        }

        //Read Bytes from File.
        public static byte[] ReadFile(string path)
        {
            try
            {
                byte[] array = new byte[0];

                FileInfo fi = new FileInfo(path);
                if (fi.Exists)
                {
                    array = File.ReadAllBytes(path);
                }
                return array;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //Get Contact Number from String.
        //public static string getContactNumber(string content)
        //{
        //    string phone = "";
        //    try
        //    {
        //        Regex[] rePhone = new Regex[2];
        //        rePhone[0] = new Regex(@"((\(\d{3}\) ?)|(\d{3}-)|\d{3})[-\. ]?\d{3}[-\. ]\d{4}");
        //        rePhone[1] = new Regex(@"((\(\d{3}\) ?)|(\d{3}-)|\d{3})[-\. ]?\d{3}[ ][-\. ][ ]\d{4}");

        //        for (int i = 0; i < rePhone.Length; i++)
        //        {
        //            MatchCollection mPh = rePhone[i].Matches(content);
        //            foreach (Match match in mPh)
        //            {
        //                if (match.Length > 10)
        //                {
        //                    phone = match.Value;
        //                    break;
        //                }
        //            }
        //            if (phone != "")
        //            {
        //                break;
        //            }
        //        }
        //    }
        //    catch
        //    {
        //    }
        //    return phone;
        //}

        public static string getName(string content)
        {
            string name = string.Empty;
            try
            {
                Regex[] reName = new Regex[1];
                reName[0] = new Regex(@"(?<FirstName>[A-Z]\.?\w*\-?[A-Z]?\w*)\s?(?<MiddleName>[A-Z]\w*|[A-Z]?\.?)\s?(?<LastName>[A-Z]\w*\-?[A-Z]?\w*)(?:,\s|)(?<Suffix>Jr\.|Sr\.|IV|III|II|)");
                for (int i = 0; i < reName.Length; i++)
                {
                    MatchCollection mEmail = reName[i].Matches(content);
                    foreach (Match match in mEmail)
                    {
                        if (match.Length > 10)
                        {
                            name = match.Value;
                            return name;
                        }
                    }
                }
            }
            catch
            {
            }
            return name;
        }

        public static string[] getContactNumber(string content)
        {
            List<string> phone = new List<string>();
            try
            {
                Regex[] rePhone = new Regex[3];
                rePhone[0] = new Regex(@"[\(|\s|]?\d{3}[\)|\-|\.|\s|]+\d{7}");
                rePhone[1] = new Regex(@"[\(|\s|]+\d{3}[\)|\-|\.|\s|]+?\d{3}[\-|\.|\s|]+\d{4}");
                rePhone[2] = new Regex(@"\d{3}[\-|\.|\,|\s|]+\d{3}[\-|\.|\,|\s|]+\d{4}");
                //rePhone[3] = new Regex(@"(\+1|1)?[ \-\.]?\(?[0-9]{3}\)?[ \-\.]?[0-9]{3}[ \-\.]?[0-9]{4}[ \.]*(ext|x)?[ \.]*[0-9]{0,5}");
               // string text = content.Replace(Environment.NewLine, " ");
                                
                for (int i = 0; i < rePhone.Length; i++)
                {                    
                    MatchCollection mPh = rePhone[i].Matches(content);
                    
                    foreach (Match match in mPh)
                    {
                        if (match.Length > 10)
                        {

                            //char[] charsToReplace = { ',', '.', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '`', '[', ']', '{', '}', ';', ':', '"', '\'',' ' };

                            string val = match.Value;

                            //foreach (char strChar in charsToReplace)
                            //{
                            //    val = val.Replace(strChar.ToString(), "");
                            //}
                            //val = string.Format(format, Convert.ToDouble(val));
                            
                            phone.Add(val);
                        }
                    }
                }
            }
            catch
            {
            }
            return phone.ToArray();
        }

        //Remove Script tags from HTML Tags
        public static string RemoveScriptTags(string content)
        {
            string[] removeElements = new string[] { "head", "script" };
            string _newString = content;
            foreach (string removeElement in removeElements)
            {
                while (_newString.ToLower().Contains("<" + removeElement.ToLower()))
                {
                    _newString = _newString.Substring(0, _newString.ToLower().IndexOf("<" + removeElement.ToLower())) + _newString.Substring(_newString.ToLower().IndexOf("</" + removeElement.ToLower() + ">") + removeElement.Length + 3);
                }
            }
            return _newString;
        }


        //Get Email from String.
        public static string getEmail(string content)
        {
            string Email = "";
            try
            {
                Regex reEmail = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
                Match m = reEmail.Match(content);
                if (reEmail.IsMatch(content))
                {
                    Email = m.Value;
                }
            }
            catch
            {
            }
            return Email;
        }
        public static string[] getEmail(string content, bool isMultiple)
        {
            List<string> Email = new List<string>();
            try
            {
                Regex[] reEmail = new Regex[2];
                reEmail[0] = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);

                for (int i = 0; i < reEmail.Length; i++)
                {
                    MatchCollection mEmail = reEmail[i].Matches(content);
                    foreach (Match match in mEmail)
                    {
                        if (match.Length > 10)
                        {
                            Email.Add(match.Value);
                        }
                    }
                }

            }
            catch
            {
            }
            return Email.ToArray();
        }

        //Get Address from String
        public static string getAddress(string content)
        {
            string Address = string.Empty;
            try
            {
                Regex[] reAddress = new Regex[7];
                reAddress[0] = new Regex(@"^[a-zA-Z0-9&#192;&#193;&#194;&#195;&#196;&#197;&#198;&#199;&#200;&#201;&#202;&#203;&#204;&#205;&#206;&#207;&#208;&#209;&#210;&#211;&#212;&#213;&#214;&#216;&#217;&#218;&#219;&#220;&#221;&#223;&#224;&#225;&#226;&#227;&#228;&#229;&#230;&#231;&#232;&#233;&#234;&#235;&#236;&#237;&#238;&#239;&#241;&#242;&#243;&#244;&#245;&#246;&#248;&#249;&#250;&#251;&#252;&#253;&#255;\.\,\-\/\']+[a-zA-Z0-9&#192;&#193;&#194;&#195;&#196;&#197;&#198;&#199;&#200;&#201;&#202;&#203;&#204;&#205;&#206;&#207;&#208;&#209;&#210;&#211;&#212;&#213;&#214;&#216;&#217;&#218;&#219;&#220;&#221;&#223;&#224;&#225;&#226;&#227;&#228;&#229;&#230;&#231;&#232;&#233;&#234;&#235;&#236;&#237;&#238;&#239;&#241;&#242;&#243;&#244;&#245;&#246;&#248;&#249;&#250;&#251;&#252;&#253;&#255;\.\,\-\/\' ]+$", RegexOptions.IgnoreCase);
                reAddress[1] = new Regex(@"\d{1,3}.?\d{0,3}\s[a-zA-Z]{2,30}\s[a-zA-Z]{2,15}", RegexOptions.IgnoreCase);
                reAddress[2] = new Regex(@"^p(ost)?[ |\.]*o(ffice)?[ |\.]*(box)?[ 0-9]*[^[a-z ]]*", RegexOptions.IgnoreCase);
                reAddress[3] = new Regex(@"^(?n:(?<address1>(\d{1,5}(\ 1\/[234])?(\x20[A-Z]([a-z])+)+ )|(P\.O\.\ Box\ \d{1,5}))\s{1,2}(?i:(?<address2>(((APT|B LDG|DEPT|FL|HNGR|LOT|PIER|RM|S(LIP|PC|T(E|OP))|TRLR|UNIT)\x20\w{1,5})|(BSMT|FRNT|LBBY|LOWR|OFC|PH|REAR|SIDE|UPPR)\.?)\s{1,2})?)(?<city>[A-Z]([a-z])+(\.?)(\x20[A-Z]([a-z])+){0,2})\, \x20(?<state>A[LKSZRAP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADL N]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD] |T[NX]|UT|V[AIT]|W[AIVY])\x20(?<zipcode>(?!0{5})\d{5}(-\d {4})?))$", RegexOptions.IgnoreCase);
                reAddress[4] = new Regex(@"^[a-zA-Z\d]+(([\'\,\.\- #][a-zA-Z\d ])?[a-zA-Z\d]*[\.]*)*$", RegexOptions.IgnoreCase);
                reAddress[5] = new Regex(@"^\s*((?:(?:\d+(?:\x20+\w+\.?)+(?:(?:\x20+STREET|ST|DRIVE|DR|AVENUE|AVE|ROAD|RD|LOOP|COURT|CT|CIRCLE|LANE|LN|BOULEVARD|BLVD)\.?)?)|(?:(?:P\.\x20?O\.|P\x20?O)\x20*Box\x20+\d+)|(?:General\x20+Delivery)|(?:C[\\\/]O\x20+(?:\w+\x20*)+))\,?\x20*(?:(?:(?:APT|BLDG|DEPT|FL|HNGR|LOT|PIER|RM|S(?:LIP|PC|T(?:E|OP))|TRLR|UNIT|\x23)\.?\x20*(?:[a-zA-Z0-9\-]+))|(?:BSMT|FRNT|LBBY|LOWR|OFC|PH|REAR|SIDE|UPPR))?)\,?\s+((?:(?:\d+(?:\x20+\w+\.?)+(?:(?:\x20+STREET|ST|DRIVE|DR|AVENUE|AVE|ROAD|RD|LOOP|COURT|CT|CIRCLE|LANE|LN|BOULEVARD|BLVD)\.?)?)|(?:(?:P\.\x20?O\.|P\x20?O)\x20*Box\x20+\d+)|(?:General\x20+Delivery)|(?:C[\\\/]O\x20+(?:\w+\x20*)+))\,?\x20*(?:(?:(?:APT|BLDG|DEPT|FL|HNGR|LOT|PIER|RM|S(?:LIP|PC|T(?:E|OP))|TRLR|UNIT|\x23)\.?\x20*(?:[a-zA-Z0-9\-]+))|(?:BSMT|FRNT|LBBY|LOWR|OFC|PH|REAR|SIDE|UPPR))?)?\,?\s+((?:[A-Za-z]+\x20*)+)\,\s+(A[LKSZRAP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])\s+(\d+(?:-\d+)?)\s*$", RegexOptions.IgnoreCase);
                reAddress[6] = new Regex(@"^[ \w]{3,}([A-Za-z]\.)?([ \w]*\#\d+)?(\r\n| )[ \w]{3,},\x20[A-Za-z]{2}\x20\d{5}(-\d{4})?$", RegexOptions.IgnoreCase);

                for (int i = 0; i < reAddress.Length; i++)
                {
                    MatchCollection mAdd = reAddress[i].Matches(content);
                    foreach (Match match in mAdd)
                    {
                        Address = match.Value;
                        break;
                    }
                    if (Address != "")
                    {
                        break;
                    }
                }
            }
            catch
            {
            }
            return Address;
        }

        public static string RemoveMultipleSpaces(string content)
        {
            return Regex.Replace(content, @"\s+", " ", RegexOptions.Multiline).Trim();
        }   

        public static List<string> getStreet(string content, bool isMultiple)
        {
            List<string> Street = new List<string>();
            try
            {
                string streetreg = "STREET|ST|DRIVE|DR|AVENUE|AVE|ROAD|RD|LOOP|COURT|CT|CIRCLE|LANE|LN|BOULEVARD|BLVD|CRESCENT|CRES|CARDINAL|APT|APARTMENT|PLACE";
                Regex[] reAddress = new Regex[2];
                //reAddress[0] = new Regex(@"^[a-zA-Z0-9&#192;&#193;&#194;&#195;&#196;&#197;&#198;&#199;&#200;&#201;&#202;&#203;&#204;&#205;&#206;&#207;&#208;&#209;&#210;&#211;&#212;&#213;&#214;&#216;&#217;&#218;&#219;&#220;&#221;&#223;&#224;&#225;&#226;&#227;&#228;&#229;&#230;&#231;&#232;&#233;&#234;&#235;&#236;&#237;&#238;&#239;&#241;&#242;&#243;&#244;&#245;&#246;&#248;&#249;&#250;&#251;&#252;&#253;&#255;\.\,\-\/\']+[a-zA-Z0-9&#192;&#193;&#194;&#195;&#196;&#197;&#198;&#199;&#200;&#201;&#202;&#203;&#204;&#205;&#206;&#207;&#208;&#209;&#210;&#211;&#212;&#213;&#214;&#216;&#217;&#218;&#219;&#220;&#221;&#223;&#224;&#225;&#226;&#227;&#228;&#229;&#230;&#231;&#232;&#233;&#234;&#235;&#236;&#237;&#238;&#239;&#241;&#242;&#243;&#244;&#245;&#246;&#248;&#249;&#250;&#251;&#252;&#253;&#255;\.\,\-\/\' ]+$", RegexOptions.IgnoreCase);
                reAddress[0] = new Regex(@"\d{1,3}.?\d{0,3}(\s[a-zA-Z]{2,30})+\s(" + streetreg + ")+", RegexOptions.IgnoreCase);
                reAddress[1] = new Regex(@"\d{1,3}.?\d{0,3}\s(" + streetreg + @")[.](\s[a-zA-Z]{2,30})", RegexOptions.IgnoreCase);
                //reAddress[3] = new Regex(@"^(?n:(?<address1>(\d{1,5}(\ 1\/[234])?(\x20[A-Z]([a-z])+)+ )|(P\.O\.\ Box\ \d{1,5}))\s{1,2}(?i:(?<address2>(((APT|B LDG|DEPT|FL|HNGR|LOT|PIER|RM|S(LIP|PC|T(E|OP))|TRLR|UNIT)\x20\w{1,5})|(BSMT|FRNT|LBBY|LOWR|OFC|PH|REAR|SIDE|UPPR)\.?)\s{1,2})?)(?<city>[A-Z]([a-z])+(\.?)(\x20[A-Z]([a-z])+){0,2})\, \x20(?<state>A[LKSZRAP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADL N]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD] |T[NX]|UT|V[AIT]|W[AIVY])\x20(?<zipcode>(?!0{5})\d{5}(-\d {4})?))$", RegexOptions.IgnoreCase);
                //reAddress[4] = new Regex(@"^[a-zA-Z\d]+(([\'\,\.\- #][a-zA-Z\d ])?[a-zA-Z\d]*[\.]*)*$", RegexOptions.IgnoreCase);
                //reAddress[0] = new Regex(@"^\s*((?:(?:\d+(?:\x20+\w+\.?)+(?:(?:\x20+STREET|ST|DRIVE|DR|AVENUE|AVE|ROAD|RD|LOOP|COURT|CT|CIRCLE|LANE|LN|BOULEVARD|BLVD)\.?)?)|(?:(?:P\.\x20?O\.|P\x20?O)\x20*Box\x20+\d+)|(?:General\x20+Delivery)|(?:C[\\\/]O\x20+(?:\w+\x20*)+))\,?\x20*(?:(?:(?:APT|BLDG|DEPT|FL|HNGR|LOT|PIER|RM|S(?:LIP|PC|T(?:E|OP))|TRLR|UNIT|\x23)\.?\x20*(?:[a-zA-Z0-9\-]+))|(?:BSMT|FRNT|LBBY|LOWR|OFC|PH|REAR|SIDE|UPPR))?)\,?\s+((?:(?:\d+(?:\x20+\w+\.?)+(?:(?:\x20+STREET|ST|DRIVE|DR|AVENUE|AVE|ROAD|RD|LOOP|COURT|CT|CIRCLE|LANE|LN|BOULEVARD|BLVD)\.?)?)|(?:(?:P\.\x20?O\.|P\x20?O)\x20*Box\x20+\d+)|(?:General\x20+Delivery)|(?:C[\\\/]O\x20+(?:\w+\x20*)+))\,?\x20*(?:(?:(?:APT|BLDG|DEPT|FL|HNGR|LOT|PIER|RM|S(?:LIP|PC|T(?:E|OP))|TRLR|UNIT|\x23)\.?\x20*(?:[a-zA-Z0-9\-]+))|(?:BSMT|FRNT|LBBY|LOWR|OFC|PH|REAR|SIDE|UPPR))?)?\,?\s+((?:[A-Za-z]+\x20*)+)\,\s+(A[LKSZRAP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])\s+(\d+(?:-\d+)?)\s*$", RegexOptions.IgnoreCase);
                //reAddress[6] = new Regex(@"^[ \w]{3,}([A-Za-z]\.)?([ \w]*\#\d+)?(\r\n| )[ \w]{3,},\x20[A-Za-z]{2}\x20\d{5}(-\d{4})?$", RegexOptions.IgnoreCase);

                for (int i = 0; i < reAddress.Length; i++)
                {
                    MatchCollection mAdd = reAddress[i].Matches(content);
                    foreach (Match match in mAdd)
                    {
                        Street.Add(match.Value);
                        //return Address.ToArray();
                    }
                }
            }
            catch
            {
            }
            return Street;
        }

        public static List<string> getZipcode(string content, bool isMultiple)
        {
            List<string> zipcode = new List<string>();
            try
            {
                Regex[] rezipcode = new Regex[2];
                rezipcode[0] = new Regex(@"([a-zA-Z][0-9][a-zA-Z])\ ?([0-9][a-zA-Z][0-9])", RegexOptions.IgnoreCase);
                rezipcode[1] = new Regex(@"^\d{5}(-\d{4})?$", RegexOptions.IgnoreCase);
                for (int i = 0; i < rezipcode.Length; i++)
                {
                    MatchCollection mAdd = rezipcode[i].Matches(content);
                    foreach (Match match in mAdd)
                    {
                        zipcode.Add(match.Value);                        
                    }
                }
            }
            catch
            {
            }
            return zipcode;
        }


        //Remove HTML Tages
        public static string RemoveHtmlTages(string contents)
        {
            string val = "";
            int k = contents.IndexOf("<body");
            val = contents.Substring(k);
            val = Regex.Replace(val, @"<(.|\n)*?>", string.Empty).Trim();
            val = val.Replace(Environment.NewLine, " ").Trim();
            val = Regex.Replace(val, @"\s+", " ", RegexOptions.Multiline).Trim();
            val = val.Replace("/", "").Trim();
            return val;
        }
        //Validate File Extention
        public static bool ValidateFileForResumeParse(string Extention)
        {
            bool IsDoc;
            switch (Extention)
            {
                case ".docx":
                case ".pdf":
                case ".zip":                
                case ".html":
                case ".htm":
                    IsDoc = true;
                    break;
                default:
                    IsDoc = false;
                    break;
            }
            return IsDoc;
        }

        public static string getJson(DataTable dt)
        {
            StringBuilder str = new StringBuilder();

            str.Append("[");

            foreach (DataRow dr in dt.Rows)
            {
                str.Append("{");

                string jsonval = "";

                jsonval = "\"title\" : \"" + dr[0] + "\" ,";
                jsonval += "\"key\" : \"" + dr[1] + "\" ";

                str.Append(jsonval);


                str.Append("},");
            }
            str.Replace(',', ']', str.Length - 1, 1);


            return str.ToString();
        }
        public static string getJsonforTree(DataTable dt)
        {
            StringBuilder str = new StringBuilder();
            str.Append("[");
            foreach (DataRow dr in dt.Rows)
            {
                str.Append("{");
                string jsonval = "";
                jsonval = "\"title\" : \"" + dr[0] + "\" ,";
                jsonval += "\"key\" : \"" + dr[1] + "\",";
                jsonval += "\"isLazy\" : true";
                str.Append(jsonval);
                str.Append("},");
            }
            str.Replace(',', ']', str.Length - 1, 1);
            return str.ToString();
        }

        public static string JsonForTree<T> (List<T> data)// T is any generic type
        {
            string jsonval = string.Empty;
            //tree
            //PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
           
            StringBuilder str = new StringBuilder();

            Type t=typeof(T);

            str.Append("[");

            foreach (T item in data)
            {
                jsonval = "";
               str.Append("{");
                
                    PropertyInfo pdisp = t.GetProperty("display_name");
                    object display_name = pdisp.GetValue(item, null);
                    PropertyInfo pname = t.GetProperty("menu_id");
                    object menu_id = pname.GetValue(item, null);

                    jsonval = "\"title\" : \"" + display_name.ToString() + "\" ,";
                    jsonval += "\"key\" : \"" + menu_id.ToString() + "\",";
                    jsonval += "\"isLazy\" : true";

                    str.Append(jsonval);
                    str.Append("},");
            }
            str.Replace(',', ']', str.Length - 1, 1);
            return str.ToString();
        }

        //List convert into DataTable
        public static DataTable ToDataTable<T>(List<T> data)// T is any generic type
        {
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));

            DataTable table = new DataTable();
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, prop.PropertyType);
            }
            object[] values = new object[props.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;
        }


        public static DataTable ToDataTable<T>(List<T> data, Dictionary<string, string> list)// T is any generic type
        {
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));

            DataTable table = new DataTable();
            foreach (var item in list)
            {
                table.Columns.Add(item.Value,typeof(string));
            }            
            object[] values = new object[list.Count];
            
            foreach (T rows in data)
            {
                int k = 0;
                for (int i = 0; i < props.Count; i++)
                {
                    if (list.ContainsKey(props[i].Name))
                    {
                        values[k] = props[i].GetValue(rows);
                        k++;
                    }                    
                }
                table.Rows.Add(values);
            }
            return table;
        }
        public static DataRow ListToDataTable(Dictionary<string, string> data, DataTable dt)// T is any generic type
        {
            DataRow dr = dt.NewRow();

            foreach (var key in data)
            {
                dr[key.Key] = key.Value;
            }
            return dr;
        }


        public static string ConvertToJsonForGrid(object obj, string TotalRecords)
        {
            string sJSON = "";
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            sJSON = oSerializer.Serialize(obj);
            sJSON = "{\"sEcho\": 4,  \"iTotalRecords\": \"" + TotalRecords + "\",  \"iTotalDisplayRecords\": \"" + TotalRecords + "\",  \"aaData\": " + sJSON + "}";
            return sJSON;
        }
        public static string ConvertToJson(object obj)
        {
            string sJSON = "";
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            sJSON = oSerializer.Serialize(obj);
            //sJSON = "{\"sEcho\": 4,  \"iTotalRecords\": \"" + TotalRecords + "\",  \"iTotalDisplayRecords\": \"" + TotalRecords + "\",  \"aaData\": " + sJSON + "}";
            return sJSON;
        }
        public static Type GetPropertyType(int type)
        {
            Type propType =null;
            switch (type)
            {
                case (int)clsConstants.Datatypes.dbString:
                    propType = typeof(String);
                    break;
                case (int)clsConstants.Datatypes.dbInt:
                    propType = typeof(Int32);
                    break;
                case (int)clsConstants.Datatypes.dbInt16:
                    propType =  typeof(Int16);
                    break;
                case (int)clsConstants.Datatypes.dbByte:
                    propType = typeof(Byte);
                    break;
                case (int)clsConstants.Datatypes.dbBool:
                    propType = typeof(Boolean); 
                    break;
                case (int)clsConstants.Datatypes.dbDateTime:
                    propType = typeof(DateTime);  
                    break;
                case (int)clsConstants.Datatypes.dbNumber:
                    propType = typeof(Double);
                    break;
                default:
                    propType = typeof(Object);
                    break;
            }
            return propType;
        }
        public static string UppercaseFirst(string strText)
        {
            string finaltext = strText.Replace("_", " ");
            return new System.Globalization.CultureInfo("en").TextInfo.ToTitleCase(finaltext.ToLower());
        } 
        //Convert Upper case of first letter
        //public static string UppercaseFirst(string s)
        //{

        //     Check for empty string.
        //    if (string.IsNullOrEmpty(s))
        //    {
        //        return string.Empty;
        //    }
        //     Return char and concat substring.
        //    return char.To(s[0]) + s.Substring(1);
        //}

        //Convert database field type according to enum

        public static int DBFieldTypetoEnum(string dbvalue)
        {
            int datatype = 0;
            switch (dbvalue)
            {
                case "int":
                    datatype = (int)clsConstants.Datatypes.dbInt;
                    break;
                case "money":
                case "decimal":
                    datatype = (int)clsConstants.Datatypes.dbNumber;
                    break;
                case "double":                
                case "float":
                    datatype = (int)clsConstants.Datatypes.dbFloat;
                    break;
                case "smallint":
                    datatype = (int)clsConstants.Datatypes.dbInt16;
                    break;
                case "varchar":
                case "char":
                case "nvarchar":
                case "xml":
                        datatype = (int)clsConstants.Datatypes.dbString;
                    break;
                case "datetime":
                    datatype = (int)clsConstants.Datatypes.dbDateTime;
                    break;
                case "time":
                    datatype = (int)clsConstants.Datatypes.dbTime;
                    break;
                case "date":
                    datatype = (int)clsConstants.Datatypes.dbDate;
                    break;
                case "bit":
                    datatype = (int)clsConstants.Datatypes.dbBool;
                    break;
                case "ddl":
                    datatype = (int)clsConstants.Datatypes.dbDropDown;
                    break;
                case "varbinary":
                    datatype = (int)clsConstants.Datatypes.dbFile;
                    break;
                case "Hidden":
                    datatype = (int)clsConstants.Datatypes.dbHidden;
                    break;
                default:
                    datatype = (int)clsConstants.Datatypes.dbString;
                    break;

            }
            return datatype;
        }

        public static string Decode(string Text)
        {
            int c = 0;
            string Temp = "";
            string Temp2 = "";

            for (int i = Text.Length-1; i >= 0; i--)
            {
                c = Convert.ToChar(Text.Substring(i, 1));
                c = (c - 26) - i;
                if (c < 0)
                    c = 256 + c;
                Temp += ((char)c).ToString();
            }
            for (int i = 0; i <= Temp.Length - 1; i++)
            {
                Temp2 += Temp[Temp.Length - 1 - i];
            }
            return Temp2;
        }

        public static string Encode(string Text)
        {
            int c = 0;
            string Temp = "";
            for (int i = 0; i <= Text.Length-1; i++)
            {
                c = Convert.ToChar(Text.Substring(i, 1));
                c = (c + 26) + i;
                if (c > 255)
                    c = c - 256;
                Temp += ((char)c).ToString();
            }
            return Temp;
        }

        public static void SerializeObject( object o,string rootElement, string path)
        {
            XmlSerializer s = new XmlSerializer(o.GetType(), new XmlRootAttribute(rootElement));
            TextWriter tw = new StreamWriter(path);
            s.Serialize(tw, o);
            tw.Close();
        }

        public static object DserializeObject(Type t,string rootElement, string path) 
        {
            
            object o = new object();
            try
            {
                XmlSerializer d = new XmlSerializer(t, new XmlRootAttribute(rootElement));
                TextReader ts = new StreamReader(path);
                o = Convert.ChangeType(d.Deserialize(ts), t);
                ts.Close();
            }
            catch
            {
                o = null;
            }
            return o;
        }

        public static string GetUniqueFileName(string name, string savePath, string ext)
        {
            name = name.Replace(ext, "").Replace(" ", "_");
            name = System.Text.RegularExpressions.Regex.Replace(name, @"[^\w\s]", "");
            var newName = name;
            var i = 0;
            if (System.IO.File.Exists(savePath + newName + ext))
            {
                do
                {
                    i++;
                    newName = name + "_" + i;
                }
                while (System.IO.File.Exists(savePath + newName + ext));

            }
            return newName + ext;
        }

        public static string setValidation(string field_name,string field_type)
        {
            string strReutn = string.Empty;
            switch(DBFieldTypetoEnum(field_type))
            {
                case 1:
                case 3:
                case 4:
                    strReutn = "number";
                    break;
                case 2:
                    if (field_name.Contains("phone") || field_name.Contains("mobile"))
                        strReutn = "phone";
                    else if (field_name.Contains("url") || field_name.Contains("website"))
                        strReutn = "url";
                    else if (field_name.Contains("email"))
                        strReutn = "email";
                    else if (field_name.Contains("password") || field_name.Contains("pwd"))
                        strReutn = "password";
                    else
                        strReutn = "text";
                    break;
                default :
                    strReutn = "text";
                    break;
            }
            return strReutn;
        }

        public static object ConvertToObject(object original, object convertto)
        {
            try
            {
                if (convertto != null)
                {
                    Type _original = original.GetType();
                    Type _convertto = convertto.GetType();
                    PropertyInfo[] properties_original = _original.GetProperties();

                    foreach (PropertyInfo item in properties_original)
                    {
                        PropertyInfo properties_convertto = _convertto.GetProperty(item.Name);
                        if (properties_convertto != null)
                        {
                            object defaultValue = item.GetValue(original, null);
                            properties_convertto.SetValue(convertto, System.Convert.ChangeType(defaultValue, item.PropertyType), null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
            return convertto;
        }

    }
}
